/**
 * 项目名：化工企业安全生产信息化管理平台
 * 日期：    2022-08-28 22:03:50
 * Copyright (c) 2015- -版权所有
 */
package com.joysuch.wwyt.baidu.controller;

import com.joysuch.wwyt.baidu.enums.BaiduCodeEnum;
import com.joysuch.wwyt.baidu.req.BaiduFace;
import com.joysuch.wwyt.baidu.req.BaiduSample;
import com.joysuch.wwyt.baidu.util.DzPrtqUtils;
import com.joysuch.wwyt.common.constant.Constant;
import com.joysuch.wwyt.core.common.ajax.ResultBean;
import com.joysuch.wwyt.core.entity.BaseConfig;
import com.joysuch.wwyt.core.entity.BaseUser;
import com.joysuch.wwyt.core.enums.BaseConfigCodes;
import com.joysuch.wwyt.core.repository.BaseUserDao;
import com.joysuch.wwyt.core.service.BaseConfigService;
import com.joysuch.wwyt.core.service.BaseImageRepositoryService;
import com.joysuch.wwyt.core.service.BaseUserFaceApiLogService;
import com.joysuch.wwyt.core.support.Context;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.io.IOException;

@RestController
@RequestMapping("/edu/prtq/face-id")
public class DzPrtqFaceController {

    private static final Logger logger = LoggerFactory.getLogger(DzPrtqFaceController.class);

    @Autowired
    private BaseConfigService baseConfigService;

    @Autowired
    private BaseUserDao baseUserDao;
    @Autowired
    private BaseImageRepositoryService baseImageRepositoryService;


    @RequestMapping("compare")
    @ResponseBody
    @ApiOperation("人脸对比")
    public Object compare(MultipartFile file) throws IOException {
        BaseConfig baiduFaceAppID = baseConfigService.findFirstConfig(BaseConfigCodes.BAIDU_FACE_ID_APP_ID);
        if (baiduFaceAppID == null || StringUtils.isBlank(baiduFaceAppID.getValue())) {
            return ResultBean.fail(4001, "人脸识别功能未启用或配置不正确，请在电脑后台的【配置管理】-【人脸识别配置】中设置。");
        }
        BaseConfig baiduFaceAppKey = baseConfigService.findFirstConfig(BaseConfigCodes.BAIDU_FACE_ID_APP_KEY);
        if (baiduFaceAppKey == null || StringUtils.isBlank(baiduFaceAppKey.getValue())) {
            return ResultBean.fail(4001, "人脸识别功能未启用或配置不正确，请在电脑后台的【配置管理】-【人脸识别配置】中设置。");
        }
        BaseConfig baiduFaceAppSecret = baseConfigService.findFirstConfig(BaseConfigCodes.BAIDU_FACE_ID_APP_SECRET);
        if (baiduFaceAppSecret == null || StringUtils.isBlank(baiduFaceAppSecret.getValue())) {
            return ResultBean.fail(4001, "人脸识别功能未启用或配置不正确，请在电脑后台的【配置管理】-【人脸识别配置】中设置。");
        }
        Long userId = Context.getCurrentUserId();
        BaseUser user = baseUserDao.getOne(userId);
        if (user.getIdCardImgId() == null) {
            return ResultBean.fail(4001, "头像不存在, 请联系管理员添加头像");
        }
        String path = baseImageRepositoryService.findAbsolutePathById(user.getIdCardImgId());
        String base = DzPrtqUtils.readFileToBase64(new FileInputStream(path));
        String upload = DzPrtqUtils.readFileToBase64(file.getInputStream());
        try {
            JSONObject json = new BaiduFace().compare(BaiduSample.client, base, upload);
            logger.debug("请求人脸返回: {}", json.toString(2));
            if (isSuccess(json)) {
                double threshold = 80;
                JSONObject jo = json.getJSONObject("result");
                Double score = jo.getDouble("score");
                BaseConfig config = baseConfigService.findConfig(Constant.APP_FACE_RECOGNITION_ACCURACY);
                if (config != null&& StringUtils.isNotBlank(config.getValue())) {
                    threshold = Double.valueOf(config.getValue());
                }
                logger.info("用户#{}人脸比对分数={}, 门限值为{}", userId, score, threshold);
                if (score >= threshold) {
                    return ResultBean.success("成功");
                }
            }
        } catch (JSONException e) {
            return ResultBean.fail(4003, "人脸识别失败，请重新再试");
        } catch (NumberFormatException e) {
            return ResultBean.fail(4003, "人脸识别失败，请重新再试");
        }
        return ResultBean.fail(4003, "人脸识别失败，请重新再试");
    }



    private boolean isSuccess(JSONObject json) {
        return json.getInt("error_code") == 0;
    }

}

